package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.PageDto;
import com.itheima.ydd.entity.Result;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.exception.ConsumerException;
import com.itheima.ydd.mapper.YddLinkMapper;
import com.itheima.ydd.service.YddLinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
@Slf4j
public class YddLinkServiceImpl extends ServiceImpl<YddLinkMapper, YddLink> implements YddLinkService {

    @Override
    public ResponseEntity<Result> findAll(Integer type, Integer page, Integer limit) {
        PageDto<YddLink> pg = new PageDto<>(page, limit);
        LambdaQueryWrapper<YddLink> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddLink::getType, type.toString());
        page(pg, wrapper);
        return ResponseEntity.ok(new Result(0, "", pg));
    }

    @Override
    public ResponseEntity<Result> add(YddLink yddLink) {
        if (StringUtils.pathEquals("1", yddLink.getType())) {
            LambdaQueryWrapper<YddLink> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YddLink::getTitle, yddLink.getTitle());
            YddLink one = getOne(wrapper);
            if (!ObjectUtils.isEmpty(one)) {
                throw new ConsumerException("该标题已存在，请重新输入");
            }
        }
        save(yddLink);
        return ResponseEntity.ok(new Result(0, "", yddLink));
    }

    @Override
    public ResponseEntity<Result> findById(Integer id) {
        YddLink yddLink = getById(id);
        return ResponseEntity.ok(new Result(0, "", yddLink));
    }

    @Override
    public ResponseEntity<Result> updateLink(YddLink yddLink) {
        YddLink link = getOne(new LambdaQueryWrapper<YddLink>().eq(YddLink::getTitle, yddLink.getTitle()));
        if (!ObjectUtils.isEmpty(link)) {
            if (!link.getId().equals(yddLink.getId())) {
                throw new ConsumerException("标题已存在，请重新输入");
            } else {
                updateById(yddLink);
                return ResponseEntity.ok(new Result(0, "", yddLink));
            }
        }
        updateById(yddLink);
        return ResponseEntity.ok(new Result(0, "", yddLink));
    }

    @Override
    public ResponseEntity<Result> delete(Integer id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new ConsumerException("请选择要删除的数据");
        }
        removeById(id);
        return ResponseEntity.ok(new Result(0, ""));
    }
}
